package org.expressme.employee.mgmt.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.expressme.employee.mgmt.Employee;
import org.expressme.employee.mgmt.Facade;

/**
 * Create a new employee.
 * 
 * @author Michael Liao (askxuefeng@gmail.com)
 */
public class CreateServlet extends HttpServlet {

    private Facade facade;

    public void setFacade(Facade facade) {
        this.facade = facade;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String name = req.getParameter("name");
            String title = req.getParameter("title");
            boolean gender = Boolean.parseBoolean(req.getParameter("gender"));
            Date birth = new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("birth"));
            Employee p = facade.createEmployee(name, title, gender, birth);
            req.setAttribute("result", p);
            req.getRequestDispatcher("/create.jsp").forward(req, resp);
        }
        catch(ParseException e) {
            throw new ServletException(e);
        }
    }

}
